<?php

namespace App\Http\Controllers\Api;

use App\Constants\CodeResponse;
use App\Http\Requests\AddressDelRequest;
use App\Http\Requests\AddressDetailRequest;
use App\Http\Requests\AddressSaveRequest;
use App\Services\AddressService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class AddressController extends ApiController
{
    public function list(): JsonResponse
    {
        $user = Auth::guard('wx')->user();
        $userId = $user->getAuthIdentifier();
        $list = AddressService::getInstance()->getListByUserId($userId);
        return $this->success($list);
    }

    public function detail(AddressDetailRequest $request): JsonResponse
    {
        $user = Auth::guard('wx')->user();
        $userId = $user->getAuthIdentifier();
        $id = $request->post('id');
        $info = AddressService::getInstance()->getById($userId,$id);
        if (is_null($info)) {
            return $this->fail(CodeResponse::ADDRESS_NOT_EXIST);
        }
        return $this->success($info);
    }

    public function  save(AddressSaveRequest $request): JsonResponse
    {
        $user = Auth::guard('wx')->user();
        $userId = $user->getAuthIdentifier();
        $id = $request->post('id');
        $name = $request->post('name');
        $province = $request->post('province');
        $city = $request->post('city');
        $country = $request->post('country');
        $address_detail = $request->post('address_detail');
        $tel = $request->post('tel');
        $area_code = $request->post('area_code');
        $postal_code = $request->post('postal_code');
        $is_default = $request->post('is_default') ?? 0;
        $data = [
            'name' => $name,
            'user_id' => $userId,
            'province' => $province,
            'city' => $city,
            'country' => $country,
            'address_detail' => $address_detail,
            'tel' => $tel,
            'area_code' => $area_code,
            'postal_code' => $postal_code,
            'is_default' => $is_default
        ];
        if (!empty($id)) {
            $flag = AddressService::getInstance()->saveById($data,$userId,$id);
            if ($flag) {
                return $this->success();
            }
            return $this->fail(CodeResponse::UPDATED_FAIL);
        } else {
            $flag = AddressService::getInstance()->create($data);
            if ($flag) {
                return $this->success();
            }
            return $this->fail(CodeResponse::CREATED_FAIL);
        }
    }

    public function delete(AddressDelRequest $request): JsonResponse
    {
        $id = $request->post('id');
        $user = Auth::guard('wx')->user();
        $userid = $user->getAuthIdentifier();
        AddressService::getInstance()->deleteById($userid,$id);
        return $this->success();
    }

}